package com.changgou.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fescar.spring.annotation.GlobalTransactional;
import com.changgou.entity.Result;
import com.changgou.goods.feign.SkuFeign;
import com.changgou.order.config.RabbitMQConfig;
import com.changgou.order.dao.*;
import com.changgou.order.pojo.*;
import com.changgou.order.service.CartService;
import com.changgou.order.service.OrderService;
import com.changgou.pay.feign.WxPayFeign;
import com.changgou.util.IdWorker;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.time.LocalDate;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private TaskMapper taskMapper;

    @Autowired
    private OrderLogMapper orderLogMapper;

    @Autowired
    private OrderConfigMapper orderConfigMapper;
    @Autowired
    private CartService cartService;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private SkuFeign skuFeign;

    @Autowired
    private WxPayFeign wxPayFeign;

    private static final String CART = "cart_";

    // 新增订单
    @Override
    @GlobalTransactional(name = "order_add")
    public String add(Order order) {
        String username = order.getUsername();
        //1.获取购物车相关数据
        Map cartMap = cartService.list(username);
        List<OrderItem> orderItemList = (List<OrderItem>) cartMap.get("orderItemList");

        //2. 统计购物车中总金额 总数量
        order.setTotalNum((Integer) cartMap.get("totalNum"));
        order.setTotalNum((Integer) cartMap.get("totalMoney"));

        //3.填充订单数据，保存到tb_order表
        order.setPayMoney((Integer) cartMap.get("totalMoney"));
        order.setCreateTime(new Date());
        order.setUpdateTime(new Date());
        order.setBuyerRate("0"); // 0:未评价  1:已评价
        order.setSourceType("1"); //1:WEB
        order.setOrderStatus("0"); //0:未完成 1:已完成 2:已退货
        order.setPayStatus("0"); //0:未支付 1:已支付
        order.setConsignStatus("0"); //0:未发货 1:已发货
        String orderId = idWorker.nextId() + "";
        order.setId(orderId);
        orderMapper.insertSelective(order);

        //4.填充订单项数据 保存到tb_order_item表（订单数据中的每个商品）
        for (OrderItem orderItem : orderItemList) {
            orderItem.setId(idWorker.nextId() + "");
            orderItem.setIsReturn("0");//0:未退货 1:已退货
            orderItem.setOrderId(orderId);
            orderItemMapper.insertSelective(orderItem);
        }

        //5. 增加任务表记录
        System.out.println("向订单任务表添加任务数据");
        Task task = new Task();
        task.setCreateTime(new Date());
        task.setUpdateTime(new Date());
        task.setMqExchange(RabbitMQConfig.EX_BUYING_ADDPOINTUSER);
        task.setMqRoutingkey(RabbitMQConfig.CG_BUYING_ADDPOINT_KEY);
        HashMap map = new HashMap();
        map.put("userName", order.getUsername());
        map.put("orderId", orderId);
        map.put("point", order.getPayMoney());//积分
        task.setRequestBody(JSON.toJSONString(map));
        taskMapper.insertSelective(task);


        //6.扣减库存并增加销量
        skuFeign.decrCount(order.getUsername());
        //7.删除Redis中购物车数据
        redisTemplate.delete(CART + order.getUsername());

        //8.发送延迟队列消息
        rabbitTemplate.convertAndSend("", "queue.ordercreate", orderId);
        return orderId;
    }

    /**
     * @param id
     * @return com.changgou.order.pojo.Order
     * @description: 根据订单id查询订单信息
     * @author 大佬味的小男孩
     * @date 2020/08/04 19:22
     */
    @Override
    public Order findById(String id) {
        Order order = orderMapper.selectByPrimaryKey(id);
        return order;
    }

    /**
     * @param orderId
     * @param transactionId
     * @return void
     * @description: 修改订单的支付状态，并记录日志
     * @author 大佬味的小男孩
     * @date 2020/08/05 15:11
     */
    @Override
    @Transactional
    public void updatePayStatus(String orderId, String transactionId) {
        Order order = orderMapper.selectByPrimaryKey(orderId);
        if (order != null && "0".equals(order.getPayStatus())) {
            //修改订单支付状态
            order.setPayStatus("1"); //已支付
            order.setOrderStatus("1");
            order.setUpdateTime(new Date()); //修改时间
            order.setPayTime(new Date()); //支付时间
            order.setTransactionId(transactionId);//微信返回的交易流水号
            orderMapper.updateByPrimaryKeySelective(order);
            //订单的支付日志
            OrderLog orderLog = new OrderLog();
            orderLog.setId(idWorker.nextId() + ""); //id
            orderLog.setOrderId(order.getId());//订单id
            orderLog.setOperater("system");// 系统
            orderLog.setOperateTime(new Date()); //系统操作时间
            orderLog.setOrderStatus("1");
            orderLog.setPayStatus("1");
            orderLog.setRemarks("支付流水号" + transactionId);

            orderLogMapper.insert(orderLog);
        }
    }

    /**
     * @param orderId
     * @return void
     * @description: 关闭订单
     * @author 大佬味的小男孩
     * @date 2020/08/06 10:50
     */
    @Override
    public void closeOrder(String orderId) {

        //1.根据订单id查询数据库中订单信息，判断订单是否存在，判断订单状态
        System.out.println("关闭订单id：" + orderId);
        Order order = orderMapper.selectByPrimaryKey(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        if ("1".equals(order.getPayStatus())) {
            System.out.println("当前订单已经支付，不需要关闭");
            return;
        }
        //2.基于微信查询订单信息
        Result result = wxPayFeign.queryOrder(orderId);
        Map resultMap = (Map) result.getData();

        if ("SUCCESS".equals(resultMap.get("trade_state"))) {
            //如果当前订单的支付状态为已支付,则进行数据补偿(mysql)
            this.updatePayStatus(orderId, (String) resultMap.get("transaction_id"));
        }
        //如果当前订单的支付状态为未支付,则修改mysql中的订单信息,新增订单日志,恢复商品的库存,基于微信关闭订单
        if ("NOTPAY".equals(resultMap.get("trade_state"))) {
            order.setUpdateTime(new Date());
            order.setOrderStatus("4"); //订单关闭
            orderMapper.updateByPrimaryKeySelective(order);

            //新增订单日志
            OrderLog orderLog = new OrderLog();
            orderLog.setId(idWorker.nextId() + "");
            orderLog.setOperater("system");//系统
            orderLog.setOperateTime(new Date());
            orderLog.setOrderStatus("4");
            orderLog.setOrderId(orderId);
            orderLogMapper.insert(orderLog);

            //恢复商品的库存
            OrderItem orderItem = new OrderItem();
            orderItem.setOrderId(orderId);
            List<OrderItem> orderItemList = orderItemMapper.select(orderItem);

            for (OrderItem item : orderItemList) {
                String skuId = item.getSkuId();
                Integer num = item.getNum();
                skuFeign.resumeStockNum(skuId, num);
            }

            //基于微信关闭订单
            wxPayFeign.close(orderId);
        }

    }


    /**
     * @param orders
     * @return void
     * @description: 批量发货
     * @author 大佬味的小男孩
     * @date 2020/08/07 09:45
     */
    @Override
    @Transactional
    public void batchSend(List<Order> orders) {
        //判断每个订单的订单号和物流公司是否存在
        for (Order order : orders) {
            if (order.getId() == null) {
                throw new RuntimeException("订单号为空");
            }
            if (order.getShippingCode() == null || order.getShippingName() == null) {
                throw new RuntimeException("请选择快递公司和填写快递单号");
            }
        }
        //进行订单状态的校验
        for (Order order : orders) {
            Order order1 = orderMapper.selectByPrimaryKey(order.getId());
            if (!"0".equals(order1.getConsignStatus()) || !"1".equals(order1.getOrderStatus())) {
                throw new RuntimeException("订单状态有误！");
            }
        }
        //修改订单状态为发货
        for (Order order : orders) {
            order.setOrderStatus("2");//订单状态已发货
            order.setConsignStatus("1");//发货状态已发货
            order.setConsignTime(new Date());//发货时间
            order.setUpdateTime(new Date());//更新时间
            orderMapper.updateByPrimaryKeySelective(order);//记录订单变动日志
            OrderLog orderLog = new OrderLog();
            orderLog.setId(idWorker.nextId() + "");
            orderLog.setOperateTime(new Date());//当前日期
            orderLog.setOperater("admin");//系统管理员
            orderLog.setOrderStatus("2");//已完成
            orderLog.setConsignStatus("1");//发状态（0未发货1已发货）
            orderLog.setOrderId(order.getId());
            orderLogMapper.insertSelective(orderLog);
        }

    }


    /**
     * @param orderId
     * @param operator
     * @return void
     * @description: 手动收货
     * @author 大佬味的小男孩
     * @date 2020/08/07 10:14
     */
    @Override
    public void confirmTask(String orderId, String operator) {
        Order order = orderMapper.selectByPrimaryKey(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        if (!"1".equals(order.getConsignStatus())) {
            throw new RuntimeException("订单未发货");
        }
        order.setConsignStatus("2");//已送达
        order.setOrderStatus("3");//已完成
        order.setUpdateTime(new Date());
        order.setEndTime(new Date());//交易结束
        orderMapper.updateByPrimaryKeySelective(order);

        //记录订单变动日志
        OrderLog orderLog = new OrderLog();
        orderLog.setId(idWorker.nextId() + "");
        orderLog.setOperateTime(new Date());//当前日期
        orderLog.setOperater(operator);//系统？管理员？用户？
        orderLog.setOrderStatus("3");
        orderLog.setOrderId(order.getId());
        orderLogMapper.insertSelective(orderLog);

    }


    /**
     * @param
     * @return void
     * @description: 自动确认收货
     * @author 大佬味的小男孩
     * @date 2020/08/07 13:13
     */
    @Override
    @Transactional
    public void autoTack() {
        //读取订单配置信息
        OrderConfig orderConfig = orderConfigMapper.selectByPrimaryKey(1);
        //获得时间节点
        LocalDate now = LocalDate.now();//当前日期
        //获取过期的时间节点，在这个日期前发货的未收货订单都
        LocalDate date = now.plusDays(-orderConfig.getTakeTimeout());
        System.out.println(date);

        //按条件查询过期订单
        Example example = new Example(Order.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andLessThan("consignTime", date);
        criteria.andEqualTo("orderStatus", "2");
        List<Order> orderList = orderMapper.selectByExample(example);

        for (Order order : orderList) {
            System.out.println("过期订单：" + order.getId() + "" + order.getConsignStatus());
            this.confirmTask(order.getId(), "system");
        }


    }

    /**
     * 构建查询对象
     *
     * @param searchMap
     * @return
     */
    private Example createExample(Map<String, Object> searchMap) {
        Example example = new Example(Order.class);
        Example.Criteria criteria = example.createCriteria();
        if (searchMap != null) {
            // 订单id
            if (searchMap.get("id") != null && !"".equals(searchMap.get("id"))) {
                criteria.andEqualTo("id", searchMap.get("id"));
            }
            // 支付类型，1、在线支付、0 货到付款
            if (searchMap.get("payType") != null && !"".equals(searchMap.get("payType"))) {
                criteria.andEqualTo("payType", searchMap.get("payType"));
            }
            // 物流名称
            if (searchMap.get("shippingName") != null && !"".equals(searchMap.get("shippingName"))) {
                criteria.andLike("shippingName", "%" + searchMap.get("shippingName") + "%");
            }
            // 物流单号
            if (searchMap.get("shippingCode") != null && !"".equals(searchMap.get("shippingCode"))) {
                criteria.andLike("shippingCode", "%" + searchMap.get("shippingCode") + "%");
            }
            // 用户名称
            if (searchMap.get("username") != null && !"".equals(searchMap.get("username"))) {
                criteria.andLike("username", "%" + searchMap.get("username") + "%");
            }
            // 买家留言
            if (searchMap.get("buyerMessage") != null && !"".equals(searchMap.get("buyerMessage"))) {
                criteria.andLike("buyerMessage", "%" + searchMap.get("buyerMessage") + "%");
            }
            // 是否评价
            if (searchMap.get("buyerRate") != null && !"".equals(searchMap.get("buyerRate"))) {
                criteria.andLike("buyerRate", "%" + searchMap.get("buyerRate") + "%");
            }
            // 收货人
            if (searchMap.get("receiverContact") != null && !"".equals(searchMap.get("receiverContact"))) {
                criteria.andLike("receiverContact", "%" + searchMap.get("receiverContact") + "%");
            }
            // 收货人手机
            if (searchMap.get("receiverMobile") != null && !"".equals(searchMap.get("receiverMobile"))) {
                criteria.andLike("receiverMobile", "%" + searchMap.get("receiverMobile") + "%");
            }
            // 收货人地址
            if (searchMap.get("receiverAddress") != null && !"".equals(searchMap.get("receiverAddress"))) {
                criteria.andLike("receiverAddress", "%" + searchMap.get("receiverAddress") + "%");
            }
            // 订单来源：1:web，2：app，3：微信公众号，4：微信小程序  5 H5手机页面
            if (searchMap.get("sourceType") != null && !"".equals(searchMap.get("sourceType"))) {
                criteria.andEqualTo("sourceType", searchMap.get("sourceType"));
            }
            // 交易流水号
            if (searchMap.get("transactionId") != null && !"".equals(searchMap.get("transactionId"))) {
                criteria.andLike("transactionId", "%" + searchMap.get("transactionId") + "%");
            }
            // 订单状态
            if (searchMap.get("orderStatus") != null && !"".equals(searchMap.get("orderStatus"))) {
                criteria.andEqualTo("orderStatus", searchMap.get("orderStatus"));
            }
            // 支付状态
            if (searchMap.get("payStatus") != null && !"".equals(searchMap.get("payStatus"))) {
                criteria.andEqualTo("payStatus", searchMap.get("payStatus"));
            }
            // 发货状态
            if (searchMap.get("consignStatus") != null && !"".equals(searchMap.get("consignStatus"))) {
                criteria.andEqualTo("consignStatus", searchMap.get("consignStatus"));
            }
            // 是否删除
            if (searchMap.get("isDelete") != null && !"".equals(searchMap.get("isDelete"))) {
                criteria.andEqualTo("isDelete", searchMap.get("isDelete"));
            }

            // 数量合计
            if (searchMap.get("totalNum") != null) {
                criteria.andEqualTo("totalNum", searchMap.get("totalNum"));
            }
            // 金额合计
            if (searchMap.get("totalMoney") != null) {
                criteria.andEqualTo("totalMoney", searchMap.get("totalMoney"));
            }
            // 优惠金额
            if (searchMap.get("preMoney") != null) {
                criteria.andEqualTo("preMoney", searchMap.get("preMoney"));
            }
            // 邮费
            if (searchMap.get("postFee") != null) {
                criteria.andEqualTo("postFee", searchMap.get("postFee"));
            }
            // 实付金额
            if (searchMap.get("payMoney") != null) {
                criteria.andEqualTo("payMoney", searchMap.get("payMoney"));
            }

        }
        return example;
    }

}
